package com.example.tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.app.MyApplication;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat")
public class Utils {
	public static SimpleDateFormat DB_TIMESTAMP_Format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	public static SimpleDateFormat LOCATION_Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@SuppressWarnings("unused")
	private static final double PI = 3.14159265;
	private static final double RAD = Math.PI / 180.0;

	private static final double EARTH_RADIUS = 6378137.0;

	// 返回单位是米
	public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
		double Lat1 = rad(latitude1);
		double Lat2 = rad(latitude2);
		double a = Lat1 - Lat2;
		double b = rad(longitude1) - rad(longitude2);
		double s = 2 * Math.asin(Math
				.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}

	public static long transDateStringToLong6(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(time).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static String transLongToDateString(long time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = new Date(time);
		return sdf.format(date);
	}

	public static String transLongToDateString5(long time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date(time);
		return sdf.format(date);
	}

	public static String transLongToDateString3(long time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date(time);
		return sdf.format(date);
	}

	public static File getOutputMediaStorageDir2() {
		File mediaStorageDir = new File(getPath());
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				return null;
			}
		}
		return mediaStorageDir;
	}

	public static String getPath() {
		String path = null;
		String packageName = "/" + MyApplication.packagename + "/";
		if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {// 判断sd卡是否存�??
			path = Environment.getExternalStorageDirectory().getAbsolutePath() + packageName;
		} else {
			path = Environment.getRootDirectory().getAbsolutePath() + packageName;
		}
		File file = new File(path);
		boolean isExist = file.exists();
		if (!isExist) {
			file.mkdirs();
		}
		return file.getPath();
	}

	public static void makeRootDirectory(String filePath) {
		File file = null;
		String newPath = null;
		String[] path = filePath.split("/");
		for (int i = 0; i < path.length; i++) {
			if (newPath == null) {
				newPath = path[i];
			} else {
				newPath = newPath + "/" + path[i];
			}
			file = new File(newPath);
			if (!file.exists()) {
				file.mkdir();
			}
		}
	}

	public static String transLongToDateString2(long time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd�?");
		Date date = new Date(time);
		return sdf.format(date);
	}

	public static long transDateStringToLong(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return sdf.parse(time).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static long transDateStringToLong5(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.parse(time).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static long transDateStringToLong2(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		try {
			return sdf.parse(time).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 根据两点间经纬度坐标（double值），计算两点间距离，单位为�??
	 * 
	 * @param lng1
	 * @param lat1
	 * @param lng2
	 * @param lat2
	 * @return
	 */
	public static double getBaiduDistance(double lng1, double lat1, double lng2, double lat2) {
		double radLat1 = lat1 * RAD;
		double radLat2 = lat2 * RAD;
		double a = radLat1 - radLat2;
		double b = (lng1 - lng2) * RAD;
		double s = 2 * Math.asin(Math.sqrt(
				Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		System.out.println(s);
		return s;
	}

	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	// public static String getVersion() {
	// String version = "";
	// try {
	// PackageManager manager = KindergartenApplication.getInstance()
	// .getApplicationContext().getPackageManager();
	// PackageInfo info = manager.getPackageInfo(KindergartenApplication
	// .getInstance().getApplicationContext().getPackageName(), 0);
	// version = info.versionName;
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return version;
	// }

	public static int getUid(Context context) {
		try {
			PackageManager pm = context.getPackageManager();
			@SuppressLint("WrongConstant") android.content.pm.ApplicationInfo ai = pm.getApplicationInfo("com.ugoodtech.android.kindergarten",
					PackageManager.GET_ACTIVITIES);
			Log.d("!!", "!!" + ai.uid);
			return ai.uid;
		} catch (android.content.pm.PackageManager.NameNotFoundException e) {
			e.printStackTrace();
			return -1;
		}
	}

	/**
	 * “android.intent.action.MEDIA_SCANNER_SCAN_DIR”：扫描指定目录
	 */
	public static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";

	public static void scanDirAsync(Context ctx, String dir) {
		Intent scanIntent = new Intent(ACTION_MEDIA_SCANNER_SCAN_DIR);
		scanIntent.setData(Uri.fromFile(new File(dir)));
		ctx.sendBroadcast(scanIntent);
	}

	/**
	 * 启动MediaScanner服务，扫描媒体文件： 程序通过发�?�下面的Intent启动MediaScanner服务扫描指定的文件或目录�??
	 * 
	 * Intent.ACTION_MEDIA_SCANNER_SCAN_FILE：扫描指定文�??
	 * 
	 * @param ctx
	 * @param filePath
	 */

	public static void scanFileAsync(Context ctx, String filePath) {
		Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		scanIntent.setData(Uri.fromFile(new File(filePath)));
		ctx.sendBroadcast(scanIntent);
	}

	/**
	 * 返回当前程序版本�??
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			// versioncode = pi.versionCode;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			Log.e("VersionInfo", "Exception", e);
		}
		return versionName;
	}

	public static int compare(String v1, String v2) {
		String s1 = normalisedVersion(v1);
		String s2 = normalisedVersion(v2);
		return s1.compareTo(s2);
	}

	public static String normalisedVersion(String version) {
		return normalisedVersion(version, ".", 4);
	}

	public static String normalisedVersion(String version, String sep, int maxWidth) {
		String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
		StringBuilder sb = new StringBuilder();
		for (String s : split) {
			sb.append(String.format("%" + maxWidth + 's', s));
		}
		return sb.toString();
	}

	public static boolean checkpwd(String pwd) {

		Pattern p = Pattern.compile("[0-9A-Za-z]*");

		Matcher m = p.matcher(pwd);

		System.out.println(m.matches() + "---");

		return m.matches();

	}

	public static boolean isSDCardExist() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	public static File getWorkDir() {
		File dir = null;
		try {
			String destDir = Environment.getExternalStorageDirectory().getPath() + File.separator + "FmsAndroid";
			dir = new File(destDir);
		} catch (Exception x) {
			dir = Environment.getDownloadCacheDirectory();
		}
		if (!dir.exists())
			dir.mkdirs();
		return dir;
	}

	public static void showToast(Context context, String text) {
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}

	public static void showToast(Context context, int resId) {
		Toast.makeText(context, context.getResources().getString(resId), Toast.LENGTH_SHORT).show();
	}

	public static String getRefreshTime() {
		return DB_TIMESTAMP_Format.format(new Date());
	}

	public static String getStandardTime() {
		return LOCATION_Format.format(new Date());
	}

	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	public static void hideSystemKeyBoard(Context context, View view) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	public static void showSystemKeyBoard(Context context, View view) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(view, 0);
	}

	public static boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
//				return mNetworkInfo.isConnected();
				return mNetworkInfo.isAvailable();
			}

//			NetworkCapabilities networkCapabilities = null;
//			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//					networkCapabilities = mConnectivityManager.getNetworkCapabilities(mConnectivityManager.getActiveNetwork());
//				}
//			}
//			if (networkCapabilities == null) {
//				System.out.println("请打开网络");
//			} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//				if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
//					System.out.println("当前使用移动网络");
//				} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
//					System.out.println("当前使用WIFI网络");
//				}
//			}

		}
		return false;
	}

	public static boolean toastIsNetworkConnected(Context context) {
		boolean l=isNetworkConnected(context);
		if (l) {
			return true;
		}
		// Toast.makeText(context, "网络连接不可�??", Toast.LENGTH_SHORT).show();
		return false;
	}

	public static void focusOnError(Context context, TextView field, int resourceId) {
		field.requestFocus();
		hideSystemKeyBoard(context, field);
		field.setError("<font color=#333333>" + context.getString(resourceId) + "</font>");
	}

	public static void focusOnError(Context context, EditText field, String message) {
		field.requestFocus();
		hideSystemKeyBoard(context, field);
		Spanned fromHtml = Html.fromHtml("<font color=#333333>" + message + "</font>");
		field.setError(fromHtml);
		// field.clearFocus();
	}

	/**
	 * Create a file Uri for saving an image or video
	 */
	public static Uri getOutputMediaFileUri() {
		File mediaFile = getOutputMediaFile();
		if (mediaFile == null) {
			return null;
		} else {
			return Uri.fromFile(mediaFile);
		}
	}

	public static File getOutputMediaStorageDir() {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.
		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"p009");

		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				return null;
			}
		}
		return mediaStorageDir;
	}

	/**
	 * Create a File for saving an image or video
	 */
	public static File getOutputMediaFile() {
		File mediaStorageDir = getOutputMediaStorageDir();
		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
		Log.d("kindergarten", "temp path:" + mediaFile.getPath());
		return mediaFile;
	}

	public static String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存�??
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目�??
		} else {
			sdDir = Environment.getRootDirectory();
		}
		return sdDir.toString();

	}

	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			System.out.println("创建目录" + destDirName + "失败，目标目录已经存�??");
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
		// 创建目录
		if (dir.mkdirs()) {
			System.out.println("创建目录" + destDirName + "成功�??");
			return true;
		} else {
			System.out.println("创建目录" + destDirName + "失败�??");
			return false;
		}
	}

	public static String getVersion() {
		String version = "";
		try {
			PackageManager manager = MyApplication.getInstance().getApplicationContext().getPackageManager();
			PackageInfo info = manager
					.getPackageInfo(MyApplication.getInstance().getApplicationContext().getPackageName(), 0);
			version = info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return version;
	}

	public static int getVersionCode() {
		int version = 0;
		try {
			PackageManager manager = MyApplication.getInstance().getApplicationContext().getPackageManager();
			PackageInfo info = manager
					.getPackageInfo(MyApplication.getInstance().getApplicationContext().getPackageName(), 0);
			version = info.versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 根据手机的分辨率�?? dp 的单�?? 转成�?? px(像素)
	 */
	public static String standardImageUrl(String url, float width, float height) {
		return url + "@" + dip2pxFinal(width) + "w_" + dip2pxFinal(height) + "h_1e_1c";
	}

	public static String standardImageUrlSuoFangdp(String url, int width) {
		return url + "@" + dip2pxFinal(width) + "w";
	}

	public static String standardImageUrlSuoFangpx(String url, int width) {
		return url + "@" + width + "w";
	}

	public static String standardImageUrlPX(String url, int width, int height) {
		return url + "@" + width + "w_" + height + "h_1e_1c";
	}

	/**
	 * 根据手机的分辨率�?? dp 的单�?? 转成�?? px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int dip2px(Context context, double dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率�?? dp 的单�?? 转成�?? px(像素)
	 */
	public static int dip2pxFinal(float dpValue) {
		return (int) (dpValue * MyApplication.density + 0.5f);
	}

	/**
	 * 根据手机的分辨率�?? px(像素) 的单�?? 转成�?? dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 删除目录（文件夹）以及目录下的文�??
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public static boolean deleteDirectory(String sPath) {
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔�??
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则�??�??
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文�??(包括子目�??)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文�??
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目�??
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除目录（文件夹）下的文�??
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public static boolean deleteDirectorySon(String sPath) {
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔�??
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则�??�??
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文�??(包括子目�??)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文�??
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目�??
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件�??
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	public static String getRealFilePath(final Uri uri, final Context ctx) {
		if (null == uri)
			return null;
		final String scheme = uri.getScheme();
		String data = null;
		if (scheme == null)
			data = uri.getPath();
		else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			data = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = ctx.getContentResolver().query(uri, new String[] { ImageColumns.DATA }, null, null, null);
			if (null != cursor) {
				if (cursor.moveToFirst()) {
					int index = cursor.getColumnIndex(ImageColumns.DATA);
					if (index > -1) {
						data = cursor.getString(index);
					}
				}
				cursor.close();
			}
		}
		return data;
	}

	public static boolean isOpenGps(Context context) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			return true;
		}
		return false;
	}

	// 捆绑安装
	public static boolean retrieveApkFromAssets(Context context, String fileName, String path) {
		boolean bRet = false;

		try {
			File file = new File(path);
			if (file.exists()) {
				return true;
			} else {
				file.createNewFile();
				InputStream is = context.getAssets().open(fileName);
				FileOutputStream fos = new FileOutputStream(file);

				byte[] temp = new byte[1024];
				int i = 0;
				while ((i = is.read(temp)) != -1) {
					fos.write(temp, 0, i);
				}
				fos.flush();
				fos.close();
				is.close();

				bRet = true;
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return bRet;
	}

	public static boolean isAppInstalled(Context context, String packagename) {
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo == null) {
			// System.out.println("没有安装");
			return false;
		} else {
			// System.out.println("已经安装");
			return true;
		}
	}


	// 两次点击按钮之间的点击间隔不能少于1000毫秒
	private static final int MIN_CLICK_DELAY_TIME = 1000;
	private static long lastClickTime;

	public static boolean isFastClick() {
		boolean flag = false;
		long curClickTime = System.currentTimeMillis();
		if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
			flag = true;
		}
		lastClickTime = curClickTime;
		return flag;
	}

}
